package org.mspring.mlog.dao.impl;

import org.mspring.mlog.dao.NodeDao;
import org.mspring.mlog.entity.Node;
import org.mspring.mlog.entity.em.NodeType;
import org.mspring.nbee.orm.dao.impl.BaseDao;
import org.mspring.nbee.orm.dao.sql.Sql;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * @author Gao Youbo
 * @since 2014-09-10 11:51:15
 */
@Repository
public class NodeDaoImpl extends BaseDao<Node> implements NodeDao {

    @Override
    public List<Node> listByRole(long roleId) {
        Sql sql = new Sql("select node.* from t_node node left join t_role_node role_node on node.id = role_node.node_id where role_node.role_id = ?", roleId);
        return super.listBySql(sql);
    }

    @Override
    public List<Node> listTreeByUser(long userId) {
        Sql sql = new Sql(
                "select node.* from t_node node left join t_role_node role_node on role_node.node_id = node.id left join t_user_role user_role on user_role.role_id = role_node.role_id where node.deleted = false and user_role.user_id = ? and node.type in (?, ?) order by node.code",
                userId, NodeType.TREE_FOLDER, NodeType.TREE_ITEM);
        return super.listBySql(sql);
    }

    @Override
    public List<Node> listTabByUser(String parent, long userId) {
        Sql sql = new Sql(
                "select node.* from t_node node left join t_role_node role_node on role_node.node_id = node.id left join t_user_role user_role on user_role.role_id = role_node.role_id where node.deleted = false and node.parent = ? and user_role.user_id = ? and node.type = ? order by node.code",
                parent, userId, NodeType.TAB);
        return super.listBySql(sql);
    }

    @Override
    public Node getOpenTab(String parent, long userId) {
        Sql sql = new Sql(
                "select node.* from t_node node left join t_role_node role_node on role_node.node_id = node.id left join t_user_role user_role on user_role.role_id = role_node.role_id where node.deleted = false and node.parent = ? and user_role.user_id = ? and node.type = ? and node.open = true order by node.code",
                parent, userId, NodeType.TAB);
        return super.findBySql(sql);
    }

    @Override
    public boolean deleteAll() {
        Sql sql = new Sql("delete from t_node");
        return super.executeUpdate(sql) > 0;
    }

}
